<template>
  <div class="app-container">
    <el-form :model="queryParams"
             ref="queryForm"
             size="small"
             :inline="true"
             v-show="showSearch"
             label-width="78px">
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreatedAt"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间">
        <el-date-picker
          v-model="daterangeUpdatedAt"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="picList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="表情包" align="center">
        <template slot-scope="scope">
          <el-image
            style="width: 70px; height: 70px"
            :src="scope.row.picUrl"
            :preview-src-list="[scope.row.picUrl]"
            :z-index="9999"
            :fit="fit">
              <div slot="error" class="image-error">
                <i class="el-icon-picture-outline"></i>
              </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          {{ getPicTypeLabel(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column label="表情包路径" align="center" prop="picUrl" />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改表情包资源明细对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      :close-on-click-modal="false"
      width="600px"
      @close="picClose()"
      append-to-body
      custom-class="emoji-dialog">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="left">

        <el-form-item label="表情包类型" prop="type">
          <el-select
            v-model="form.type"
            clearable
            filterable
            @change="typeChange"
            placeholder="请选择表情包类型"
            size="small"
            class="full-width-select">
            <el-option
              v-for="item in picTypeDict"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="上传表情包">
          <el-upload
            ref="uploadPic"
            multiple
            :limit="100"
            :action="uploadPic.url"
            accept=".jpg,.png,.jpeg,.gif,.webp"
            :headers="headers"
            :file-list="uploadPic.fileList"
            :on-progress="handlePicUploadPackage"
            :on-success="handlePicSuccessPackage"
            :before-upload="beforePicUpload"
            drag
            list-type="picture-card"
            class="emoji-uploader">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              <div>将文件拖到此处，或</div>
              <em>点击选择文件</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              支持 JPG/PNG/JPEG/GIF/WEBP 格式，单个文件不超过 5MB
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="submitCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listPic, getPic, delPic, addPic, updatePic } from "@/api/pic"
import {getToken} from "@/utils/auth";

export default {
  name: "Pic",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表情包资源明细表格数据
      picList: [],
      fit:'fill',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 更新时间时间范围
      daterangeCreatedAt: [],
      // 更新时间时间范围
      daterangeUpdatedAt: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        createdAt: null,
        updatedAt: null
      },
      // 表单参数
      form: {
        type:'',
      },
      //表情包上传进度条
      uploading:null,
      picUrlList:[],
      // 表情包上传
      uploadPic: {
        // 是否禁用上传
        isUploading: false,
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/pic/pic/upload",
        // 上传的文件列表
        fileList: []
      },
      multipartFile:{
        isTypeChannel :0,
        status:0,
      },
      // 设置上传的请求头部
      headers: {Authorization: "Bearer " + getToken()},
      //表情包类型字典
      picTypeDict:[],
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getList()
    this.initDict()
  },
  methods: {
    initDict() {
      const dicts = [
        { name: "pic_type", prop: "picTypeDict" },
      ];
      return Promise.all(dicts.map(dict => this.loadDict(dict.name, dict.prop)));
    },
    loadDict(dictName, targetProp) {
      return this.getDicts(dictName).then(res => {
        this[targetProp] = (res.data || []).map(item => ({
          label: item.dictLabel,
          value: item.dictValue
        }));
      }).catch(() => {
        this[targetProp] = [];
      });
    },
    /** 查询表情包资源明细列表 */
    getList() {
      this.loading = true
      let param = this.queryParams
      listPic(param).then(response => {
        this.picList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        picUrl: null,
        createdAt: null,
        updatedAt: null
      }
      this.resetForm("form")
      this.uploadPic.fileList = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreatedAt = []
      this.daterangeUpdatedAt = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 根据 type 值匹配对应的 label
    getPicTypeLabel(typeValue) {
      const foundItem = this.picTypeDict.find(item => item.value === String(typeValue));
      return foundItem ? foundItem.label : '未知类型';
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加表情包资源明细"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPic(id).then(response => {
        debugger
        this.form = response.data
        this.open = true
        this.title = "修改表情包资源明细"
        this.form.type = response.data.type.toString();

        // 设置已上传的图片
        this.uploadPic.fileList = [{
          name: response.data.picName || '已上传图片', // 图片名称
          url: response.data.picUrl, // 图片URL
          status: 'success', // 上传状态
          uid: response.data.id // 唯一标识
        }];

      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            let param = {}
            param.id = this.form.id
            param.type = this.form.type
            param.picUrlList = this.picUrlList
            updatePic(param).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            let param = {}
            param.type = this.form.type
            param.picUrlList = this.picUrlList
            debugger
            addPic(param).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    //提交取消
    submitCancel(){
      this.open = false
      this.uploadPic.fileList = []
    },
    //类型选择
    typeChange(row){
      debugger
      console.log(row)
      console.log(this.form.type)
    },
    // 删除单个表情包
    removeEmoji(index) {
      this.uploadPic.fileList.splice(index, 1)
    },
    // 上传前校验
    beforePicUpload(file) {
      const isImage = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过5MB!')
      }
      console.log(this.uploadPic.fileList )
      return isImage && isLt5M
    },
    picClose(){
      this.form.type = null
      this.uploadPic.fileList = []
    },
    // 上传进度处理
    handlePicUploadPackage(event, file, fileList) {
      this.uploading = true
      // 可以在这里添加进度条显示逻辑
    },

    // 上传成功处理
    handlePicSuccessPackage(response, file, fileList) {
      console.log(response,file,fileList)
      if(response.code == 200){
        //存储上传的图片名称
        this.picUrlList.push(response.data);
      }
      // 处理上传成功的逻辑
      this.uploading = false
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      const picUrl = row.picUrl
      let query = {}
      query.picUrl = picUrl
      debugger
      this.$modal.confirm('是否确认删除表情包资源明细编号为"' + ids + '"的数据项？').then(function() {
        return delPic(ids,query)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pic/pic/export', {
        ...this.queryParams
      }, `pic_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped>
.emoji-dialog {
  .full-width-select {
    width: 100%;
  }

  .emoji-uploader {
    width: 100%;

    .el-upload {
      width: 100%;
    }

    .el-upload-dragger {
      width: 100%;
      padding: 20px;
    }
  }

  .emoji-preview-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    max-height: 300px;
    overflow-y: auto;
    padding: 10px 0;

    .emoji-preview-item {
      position: relative;
      width: 80px;
      height: 80px;

      .emoji-thumbnail {
        width: 100%;
        height: 100%;
        object-fit: contain;
        border-radius: 4px;
        border: 1px solid #eee;
      }

      .emoji-actions {
        position: absolute;
        top: -10px;
        right: -10px;
        opacity: 0;
        transition: opacity 0.3s;
      }

      &:hover .emoji-actions {
        opacity: 1;
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>
